package ar.com.spsolutions.splibrary.services;

import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.springframework.transaction.annotation.Transactional;

import ar.com.spsolutions.splibrary.author.Author;
import ar.com.spsolutions.splibrary.book.Book;
import ar.com.spsolutions.splibrary.book.BookBuilder;
import ar.com.spsolutions.splibrary.repositories.BookRepository;

/**
 * @Author leezsi
 */
@Path("/books")
public class RetriveAllRESTService {

	private BookRepository bookRepository;

	@GET
	@Path("/findAll")
	@Produces("application/json")
	@Transactional
	public List<RESTBook> getAllBooks() {
		final List<Book> books = this.getBookRepository().findAll();
		return RESTBook.wrapp(books);
	}

	@GET
	@Path("/byTitle/{title}")
	@Produces("application/json")
	public List<RESTBook> getBooksByTitle(
			@DefaultValue("") @PathParam("title") final String title) {
		final List<Book> books = this.getBookRepository()
				.findByTitleLike(title);
		return RESTBook.wrapp(books);
	}

	@POST
	@Path("/title/{title}/author/{author}/isbn/{isbn}")
	@Produces("application/json")
	@Transactional
	public boolean addBook(
			@DefaultValue("") @PathParam("title") final String title,
			@DefaultValue("") @PathParam("author") final String author,
			@DefaultValue("") @PathParam("isbn") final String isbn) {
		try {
			final Book book = new BookBuilder(null)//
					.withAuthor(new Author(author))//
					.withTitle(title)//
					.withIsbn(isbn)//
					.build();
			this.getBookRepository().save(book);
		} catch (final Exception e) {
			return false;
		}
		return true;
	}

	public BookRepository getBookRepository() {
		return this.bookRepository;
	}

	public void setBookRepository(final BookRepository bookRepository) {
		this.bookRepository = bookRepository;
	}

}
